<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomAction from './components/RoomAction.vue'
import RoomMessage from './components/RoomMessage.vue'
import io, { Socket } from 'socket.io-client'
import { onMounted, ref, nextTick } from 'vue'
import { baseURL } from '@/utils/request'
import { useStore } from '@/stores'
import { useRoute } from 'vue-router'
import { onUnmounted } from 'vue'
import type { TimeMessages, Message } from '@/types/room'
import { MsgType } from '@/enums'
import { getConsultOrderDetail } from '@/services/consult'
import type { ConsultOrderItem, Image } from '@/types/consult'
import dayjs from 'dayjs'
import { showToast } from 'vant'
import { provide } from 'vue'
const { user } = useStore()
const route = useRoute()
const msgList = ref<Message[]>([])
let socket: Socket
let lock = ref(true)
onMounted(() => {
  // 1. 建立连接
  socket = io(baseURL, {
    auth: {
      token: `Bearer ${user.user?.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })
  // 2. 监听连接是否成功
  socket.on('connect', () => {
    console.log('连接成功')
  })
  // 3. 监听连接失败
  socket.on('error', () => {
    console.log('连接失败')
  })
  // 5. 监听断开连接
  socket.on('disconnect', () => {
    console.log('连接已断开')
    // 端口链接后将聊天记录清空
    msgList.value = []
  })
  // 接收默认聊天消息/下拉被动接收消息
  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    // console.log(data) // data是一个聊天消息分组(目前只有一项), 暂且只处理一次, 后期再来修改成循环处理消息分组
    if (!data.length) {
      // 关闭loading
      loading.value = false
      return showToast('没有更多消息了')
    }
    // 将所有的消息设置为已读
    const items = data[data.length - 1].items
    socket.emit('updateMsgStatus', items[items.length - 1].id)
    const arr: Message[] = []
    data.forEach((item, i) => {
      // 记录第0条消息的时间
      if (i === 0) time.value = item.createTime
      const o = {
        msgType: MsgType.Notify,
        msg: {
          content: item.createTime
        },
        id: item.createTime,
        createTime: item.createTime
      }
      // 遍历聊天记录， 给第一次默认的聊天记录添加notScroll为false, 后续加载的历史聊天记录 notScroll设置为true
      item.items.forEach((listItem) => {
        listItem.notScroll = lock.value === false
      })
      arr.push(o, ...item.items) // 处理追加系统提示消息
    })
    // console.log(arr)
    msgList.value.unshift(...arr) ///  前置追加历史聊天记录
    // msgList.value = arr /// 坑?????
    loading.value = false
    // 获取了第一次默认的消息后将滚动条设置到页面的最底部  后续加载历史聊天记录的不需要再滚动到底部了
    if (lock.value) {
      nextTick(() => {
        window.scrollTo(0, document.body.scrollHeight)
      })
      lock.value = false
    }
    // 获取订单详情
    getDetail()
  })

  // 监听订单状态发生变化
  socket.on('statusChange', () => {
    console.log('订单状态变化了')
    // 重新获取一次订单状态
    getDetail()
  })

  // 接收服务器回的消息, 并追加到消息列表中
  socket.on('receiveChatMsg', (e: Message) => {
    msgList.value.push(e)
    // 更新单个聊天消息状态
    socket.emit('updateMsgStatus', e.id)
    //  接收到消息 设置滚动条到最底部
    nextTick(() => {
      // console.log('滚动滚动条')
      window.scrollTo(0, document.body.scrollHeight)
    })
  })
})
// 4.离开页面断开链接
onUnmounted(() => {
  socket.close()
})
const orderDetail = ref<ConsultOrderItem>() // 订单详情
// 获取订单详情
const getDetail = async () => {
  const res = await getConsultOrderDetail({
    orderId: route.query.orderId as string
  })
  orderDetail.value = res.data
}
// 发送文本消息给医生
const sendText = (text: string) => {
  socket.emit('sendChatMsg', {
    from: user.user?.id,
    to: orderDetail.value?.docInfo?.id,
    msgType: MsgType.MsgText,
    msg: {
      content: text
    }
  })
}
// 发送图片消息给医生
const sendImg = (obj: Image) => {
  socket.emit('sendChatMsg', {
    from: user.user?.id,
    to: orderDetail.value?.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: {
      picture: obj
    }
  })
}

// 下拉刷新获取更多聊天记录
const loading = ref(false)
const time = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))
console.log(time.value)
const onRefresh = () => {
  console.log('下拉刷新了')
  // 发送请求获取更多聊天记录
  socket.emit('getChatMsgList', 20, time.value, route.query.orderId)
}

// 依赖注入
provide('orderDetail', orderDetail)
// 修改评分的方法
const changeEvaluStatus = (score: number) => {
  // 1. 找到评价的消息
  const o = msgList.value.find((item) => item.msgType === MsgType.CardEvaForm)
  if (o) {
    // 2. 在这个消息中的mgs中 新增一个对象 evaluteDoc.score
    o.msg.evaluateDoc = {}
    o.msg.evaluateDoc.score = score
    // 3. 将评价的那条消息的msgType改成24
    o.msgType = MsgType.CardEva
  }
}
provide('changeEvaluStatus', changeEvaluStatus)
</script>

<template>
  <div class="room-page">
    <cp-nav-bar title="问诊室" />
    <room-status
      :status="orderDetail?.status"
      :time="orderDetail?.countdown"
    ></room-status>
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <room-message :msgList="msgList"></room-message>
    </van-pull-refresh>
    <room-action
      :status="orderDetail?.status"
      @sendText="sendText"
      @sendImg="sendImg"
    ></room-action>
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
